package com.jia.chenjiaweb.controller;

import com.jia.controller.BaseController;
import com.jia.utils.AjaxResult;
import com.jia.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import static com.jia.utils.AjaxResult.success;

@Slf4j
@Controller
public class UserLogincontroller extends BaseController {
    @RequestMapping({"/login", "/"})
    public String login() {
        log.info("跳转登录界面");
        return "login";
    }


    @RequestMapping("/index")
    public String index() {
        log.info("跳转成功界面");
        return "index";
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();//取出当前验证主体
        if (subject != null) {
            subject.logout();//不为空，执行一次logout的操作，将session全部清空
        }
        return "login";
    }

    @RequestMapping("unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    @RequestMapping("/register")
    public String register() {
        log.info("跳转注册界面");
        return "register";
    }


    /*
     * 整个form表单的验证流程：
     *
     * 将登陆的用户/密码传入UsernamePasswordToken，当调用subject.login(token)开始，调用Relam的doGetAuthenticationInfo方法，开始密码验证
     * 此时这个时候执行我们自己编写的CredentialMatcher（密码匹配器），执行doCredentialsMatch方法，具体的密码比较实现在这实现
     *
     * */
//   @RequiresPermissions("mail:info:edit")//判断权限字符串
    @RequestMapping("/loginUser")
    public String loginUser(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            System.out.println("获取到信息，开始验证！！");
            subject.login(token);//登陆成功的话，放到session中
            return "index";
        } catch (UnknownAccountException e) {
            log.error("账号错误");
        } catch (IncorrectCredentialsException e) {
            log.error("密码错误");
        }
        return "login";
    }


}
